package net.seabook.games.tetris;

import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import net.seabook.games.tetris.model.PieceGenerator;
import net.seabook.games.tetris.model.SettingSystem;
import net.seabook.games.tetris.model.TetrisBoard;
import net.seabook.games.tetris.ui.CanvasPanel;
import net.seabook.games.tetris.ui.ControlPanel;
import net.seabook.games.tetris.ui.PreviewPanel;

public class MainFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	
	private static JPanel mainPanel;
	private CanvasPanel canvasPanel;
	private ControlPanel controlPanel;
	private PreviewPanel previewPanel;
	private PieceGenerator generator;
	
	private TetrisBoard tBoard;
	private SettingSystem settingSystem;
	
	public MainFrame() {
		settingSystem = new SettingSystem();
		tBoard = new TetrisBoard();
		tBoard.setSettingSystem(settingSystem);
		// generate random pieces;
		generatePieces();
		initCanvasPanel();
		previewPanel = new PreviewPanel(generator.getPreviewPiece());
		previewPanel.setGenerator(generator);
		controlPanel = new ControlPanel(settingSystem);
		
		assemblePanels();
	}

	private void generatePieces() {
		generator = new PieceGenerator();
		generator.setBoard(tBoard);
		generator.generatePreviewPiece();
		generator.generateRandomPiece();
	}

	private void initCanvasPanel() {
		canvasPanel =  new CanvasPanel(generator.getPiece(), tBoard);
		canvasPanel.setGenerator(generator);
		canvasPanel.setScoreSystem(settingSystem);
	}
	
	private void assemblePanels() {
		mainPanel = new JPanel(new FlowLayout());
		
		// Put everything together.
		JPanel setup = new JPanel();
		setup.setLayout(new GridLayout(0, 1));
		
		setup.add(previewPanel);
		setup.add(controlPanel);

		mainPanel.add(canvasPanel);
		mainPanel.add(setup);
	}
	
	public static void main(String[] args) {
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}
	private static void createAndShowGUI() {
		JFrame frame = new MainFrame();
		frame.setTitle("Seabook's Java Tetris");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(mainPanel);
		
		frame.setResizable(false);
		frame.pack();
		frame.setVisible(true);
	}

}
